/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.anny.wxuser.web;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.anny.shop.entity.AnnyShop;
import com.jeeplus.modules.anny.wxuser.entity.AnnyWxUser;
import com.jeeplus.modules.anny.wxuser.service.AnnyWxUserService;

/**
 * 微信对应用户Controller
 *
 * @author linzx
 * @version 2018-10-19
 */
@Controller
@RequestMapping(value = "${adminPath}/anny/wxuser/annyWxUser")
public class AnnyWxUserController extends BaseController {

    @Autowired
    private AnnyWxUserService annyWxUserService;


    private static final double EARTH_RADIUS = 6378.137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    @ModelAttribute
    public AnnyWxUser get(@RequestParam(required = false) String id) {
        AnnyWxUser entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = annyWxUserService.get(id);
        }
        if (entity == null) {
            entity = new AnnyWxUser();
        }
        return entity;
    }

    /**
     * 更改昵称
     *
     * @param wxOpenId
     */
    @RequestMapping(value = "setNickName")
    public void setNickName(String wxOpenId) {

        annyWxUserService.setNickName(wxOpenId);
    }

    /**
     * 用户定位
     *
     * @param lat
     * @param lng
     */
    public AnnyShop userLocation(String lat, String lng) {

        double userlat = rad(Double.parseDouble(lat));
        double usering = rad(Double.parseDouble(lng));
        List<AnnyShop> shop = annyWxUserService.selectShopLocation();
        //经度相减
        double a;
        //维度相减
        double b;
        //方法正玄/2
        double sa2;
        //方法正玄/2
        double sb2;
        //相减距离
        double d = 0;
        AnnyShop s = null;
        for (AnnyShop annyShop : shop) {
            s=annyShop;
            double shoplat = rad(Double.parseDouble(annyShop.getLat()));
            double shoplng = rad(Double.parseDouble(annyShop.getLng()));
            a = userlat - shoplat;
            b = usering - shoplng;

            sa2 = Math.sin(a / 2.0);
            sb2 = Math.sin(b / 2.0);

            d = 2 * EARTH_RADIUS * Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(userlat) * Math.cos(shoplat) * sb2 * sb2));

        }
        if (d<=3){
            return s;
        }else {
            return null;
        }
    }



    /**
     * 查询所有用户数
     *
     * @return
     */
    public int wxUserALl() {
        List<AnnyWxUser> user = annyWxUserService.wxUserALl();
        int wxUserNum = user.size();
        return wxUserNum;
    }

    /**
     * 用户列表页面
     */
    @RequiresPermissions("anny:wxuser:annyWxUser:list")
    @RequestMapping(value = {"list", ""})
    public String list(AnnyWxUser annyWxUser, Model model) {
    	model.addAttribute("annyWxUser", annyWxUser);
        return "modules/anny/wxuser/annyWxUserList";
    }

    /**
     * 用户列表数据
     */
    @ResponseBody
    @RequiresPermissions("anny:wxuser:annyWxUser:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(AnnyWxUser annyWxUser, HttpServletRequest request, HttpServletResponse response, Model model) {
    	try {
			request.setCharacterEncoding("utf-8");
			annyWxUser.setNickName(new String(request.getParameter("nickName").getBytes("iso8859-1"),"utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
    	Page<AnnyWxUser> page = annyWxUserService.findPage(new Page<AnnyWxUser>(request, response), annyWxUser);
        return getBootstrapData(page);
    }

    /**
     * 查看，增加，编辑用户表单页面
     */
    @RequiresPermissions(value = {"anny:wxuser:annyWxUser:view", "anny:wxuser:annyWxUser:add", "anny:wxuser:annyWxUser:edit"}, logical = Logical.OR)
    @RequestMapping(value = "form")
    public String form(AnnyWxUser annyWxUser, Model model) {
        model.addAttribute("annyWxUser", annyWxUser);
        if (StringUtils.isBlank(annyWxUser.getId())) {//如果ID是空为添加
            model.addAttribute("isAdd", true);
        }
        return "modules/anny/wxuser/annyWxUserForm";
    }
    
    /**
     * 查看用户表单页面
     */
    @RequestMapping(value = "form1")
    public String form1(AnnyWxUser annyWxUser, Model model) {
        model.addAttribute("annyWxUser", annyWxUser);
        if (StringUtils.isBlank(annyWxUser.getId())) {//如果ID是空为添加
            model.addAttribute("isAdd", true);
        }
        return "modules/anny/wxuser/annyWxUserForm";
    }
    

    /**
     * 保存用户
     */
    @RequiresPermissions(value = {"anny:wxuser:annyWxUser:add", "anny:wxuser:annyWxUser:edit"}, logical = Logical.OR)
    @RequestMapping(value = "save")
    public String save(AnnyWxUser annyWxUser, Model model, RedirectAttributes redirectAttributes) throws Exception {
        if (!beanValidator(model, annyWxUser)) {
            return form(annyWxUser, model);
        }
        //新增或编辑表单保存
        annyWxUserService.save(annyWxUser);//保存
        addMessage(redirectAttributes, "保存用户成功");
        return "redirect:" + Global.getAdminPath() + "/anny/wxuser/annyWxUser/?repage";
    }

    /**
     * 删除用户
     */
    @ResponseBody
    @RequiresPermissions("anny:wxuser:annyWxUser:del")
    @RequestMapping(value = "delete")
    public AjaxJson delete(AnnyWxUser annyWxUser, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        annyWxUserService.delete(annyWxUser);
        j.setMsg("删除用户成功");
        return j;
    }

    /**
     * 批量删除用户
     */
    @ResponseBody
    @RequiresPermissions("anny:wxuser:annyWxUser:del")
    @RequestMapping(value = "deleteAll")
    public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String idArray[] = ids.split(",");
        for (String id : idArray) {
            annyWxUserService.delete(annyWxUserService.get(id));
        }
        j.setMsg("删除用户成功");
        return j;
    }

    /**
     * 导出excel文件
     */
    @ResponseBody
    @RequiresPermissions("anny:wxuser:annyWxUser:export")
    @RequestMapping(value = "export", method = RequestMethod.POST)
    public AjaxJson exportFile(AnnyWxUser annyWxUser, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "用户" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            Page<AnnyWxUser> page = annyWxUserService.findPage(new Page<AnnyWxUser>(request, response, -1), annyWxUser);
            new ExportExcel("用户", AnnyWxUser.class).setDataList(page.getList()).write(response, fileName).dispose();
            j.setSuccess(true);
            j.setMsg("导出成功！");
            return j;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导出用户记录失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    /**
     * 导入Excel数据
     */
    @RequiresPermissions("anny:wxuser:annyWxUser:import")
    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<AnnyWxUser> list = ei.getDataList(AnnyWxUser.class);
            for (AnnyWxUser annyWxUser : list) {
                try {
                    annyWxUserService.save(annyWxUser);
                    successNum++;
                } catch (ConstraintViolationException ex) {
                    failureNum++;
                } catch (Exception ex) {
                    failureNum++;
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条用户记录。");
            }
            addMessage(redirectAttributes, "已成功导入 " + successNum + " 条用户记录" + failureMsg);
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入用户失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/anny/wxuser/annyWxUser/?repage";
    }

    /**
     * 下载导入用户数据模板
     */
    @RequiresPermissions("anny:wxuser:annyWxUser:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "用户数据导入模板.xlsx";
            List<AnnyWxUser> list = Lists.newArrayList();
            new ExportExcel("用户数据", AnnyWxUser.class, 1).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/anny/wxuser/annyWxUser/?repage";
    }

}